<template>
  <div class="url-picture-upload">
    <a-input-group compact>
      <a-input
        v-model:value="fileUrl"
        style="width: calc(100% - 120px)"
        placeholder="输入图片网页地址上传"
        allow-clear
      />
      <a-button
        :icon="h(UploadOutlined)"
        type="primary"
        style="width: 120px"
        :loading="loading"
        @click="handleUpload"
      >
        上传
      </a-button>
    </a-input-group>
    <div class="img-wrapper">
      <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, h } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined, CloudUploadOutlined } from '@ant-design/icons-vue'
import { uploadPictureByUrlUsingPost } from '@/api/pictureController.ts'

const loading = ref<boolean>(false)

/**
 * Props 接口定义了组件期望接收两个 props：picture，onSuccess。
 * 通过 defineProps<Props>()，组件就可以接收并按照这个类型定义来校验传入的 props。
 */
interface Props {
  picture?: API.PictureVO
  // 图片上传成功后 通过这个函数传递新的图片返回展示
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()

const fileUrl = ref<string>()

/**
 * 图片地址上传
 */
const handleUpload = async () => {
  loading.value = true
  try {
    const params: API.PictureUploadRequest = { fileUrl: fileUrl.value }
    params.spaceId = props.spaceId
    // 如果是更新图片
    if (props.picture) {
      params.id = props.picture.id
    }
    const res = await uploadPictureByUrlUsingPost(params)
    // @ts-ignore
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功，可以填表编辑图片信息')
      // @ts-ignore
      props.onSuccess?.(res.data.data)
    } else {
      // @ts-ignore
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    // @ts-ignore
    message.error('图片上传失败，' + error.message)
  }
  loading.value = false
}
</script>
<style scoped>
.url-picture-upload {
  margin-bottom: 10px;
}

.url-picture-upload img {
  max-width: 100%;
  max-height: 360px;
}

.url-picture-upload .img-wrapper {
  text-align: center;
  margin-top: 10px;
}
</style>
